package interview;

public class interview_02_08 {
    public ListNode detectCycle(ListNode head) {
        ListNode p=head;
        ListNode q=head;

        if(head==null) return null;
        if(p.next==null) return null;
        p=p.next;
        q=q.next;
        if(q.next==null) return null;
        q=q.next;
        while(p!=q){
            p=p.next;
            if(q.next==null) return null;
            q=q.next;
            if(q.next==null) return null;
            q=q.next;
        }
        p=head;
        while(p!=q){
            p=p.next;
            q=q.next;
        }
        return p;
    }
}
